/**
 * 用户信息
 */
import cookie from './cookie'
import tool from './tool'
// cookie 存储key
const userKey = 'u' + tool.hash(navigator.userAgent.substr(0, 50))

class User {
  uid
  id
  code
  userName
  mobile
  accountUID
  userType
  userTypes
  tempID
  token
  trustUserUID
  /**
   * 从 cookie 获取用户信息
   */
  constructor () {
    let info = cookie.get(userKey)
    if (info != null) {
      try {
        this.setData(JSON.parse(tool.decrypto(info, 123, 25)), false)
      } catch (err) {
        console.log(err)
      }
    }
  }
  /**
   * 设置用户信息到 cookie
   * @param {*} info
   * @param {*} setCookie
   */
  setData (info, setCookie = true) {
    if (info.uid) this.uid = info.uid
    if (info.id) this.id = info.id
    if (info.code) this.code = info.code
    if (info.userName) this.userName = info.userName

    if (info.mobile) this.mobile = info.mobile.substr(0, 3) + '****' + info.mobile.substr(8, 3)
    if (info.accountUID) this.accountUID = info.accountUID
    if (info.userType) this.userType = info.userType
    if (info.userTypes) this.userTypes = info.userTypes
    if (info.tempID) this.tempID = info.tempID
    if (info.token) this.token = info.token
    if (info.trustUserUID) this.trustUserUID = info.trustUserUID
    if (setCookie) {
      cookie.set(userKey, tool.encrypto(JSON.stringify(info), 123, 25), 0)
    }
  }
  // 退出，删除cookie
  logout () {
    this.uid = null
    cookie.delete(userKey)
  }
}

export default new User()
